// depend on jquery and jquery form plugins
$(document).ready(function() {
    $("div.img-uploader").each(function(index) {
        $(this).append("<span class=\"iconadd ui-icon ui-icon-plusthick\" style='display: inline-block;' />");
        $(this).append("<span class=\"loading invisible\" style='display: inline-block;'>0%</span>");
        var div = $(this);
        var form = $(this).siblings("form.img-uploader")[0];
        var iconadd = $(this).find(".iconadd")[0];
        if ($(div).css("background-image") !== "none") {
            $(iconadd).addClass("invisible");
        }
        var loading = $(this).find(".loading")[0];
        var makeThumb = $(this).hasClass("makethumb");
        $(form).prepend("<input class=\"hidden\" type=\"file\" name=\"file\" accept=\"image/*\" />");
        $(this).append("<input type=\"hidden\" name=\"tempname\" value=\"\" />");
        var input = $(form).children("input[type='file']")[0];
        var tempName = $(this).children("input[type='hidden']")[0];
        $(this).click(function() {
            $(input).trigger("click");
        });
        $(input).change(function() {
            $(form).submit();
        });
        $(form).ajaxForm({
            beforeSend: function()
            {
                $(iconadd).addClass("invisible");
                $(loading).removeClass("invisible");
                $(div).css("background-image", "none");
                $(div).css("background-repeat", "no-repeat");
            },
            uploadProgress: function(event, position, total, percentComplete)
            {
                $(loading).text(percentComplete + " %");
            },
            error: function() {
                $(iconadd).removeClass("invisible");
                $(loading).addClass("invisible");
            },
            complete: function(response)
            {
                //alert(response.responseText);
                var resObj = $.parseJSON(response.responseText);
                $(tempName).val(resObj.tempname);
                if (resObj.success) {
                    $(iconadd).addClass("invisible");
                    $(loading).addClass("invisible");
                    $(div).css("background-image", "url('" + resObj.src + (makeThumb ? "tmb" : "") + "')");
                    if ($(div).attr("afterupload")) {
                        try {
                            eval($(div).attr("afterupload"));
                        } catch (err) {
                            console.log("fail to execute" + $(div).attr("afterupload"));
                        }
                    }
                } else {
                    $(iconadd).removeClass("invisible");
                    $(loading).addClass("invisible");
                    $(div).css("background-image", "none");
                    alert(resObj.message);
                }
            }
        });
    });
});